package month1;

import java.util.*;

public class CombinationSum39_06 {
    public static void main(String[] args) {
        System.out.println(combinationSum(new int[]{2, 3, 6, 7}, 7));
    }

    /**
     * 回溯枚举
     * @param candidates
     * @param target
     * @return
     */
    static List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> ret = new ArrayList<>();
        Arrays.sort(candidates);
        traceback(candidates, target, ret, new ArrayList(), 0);
        return ret;
    }

    static void traceback(int[] candidates, int target, List<List<Integer>> ret, List<Integer> tmp, int j) {
        if (target <= 0) {
            if (target == 0) {
                ret.add(new ArrayList(tmp));
            }
            return;
        }
        for (int i = j; i < candidates.length; ++i) {
            if (target - candidates[i] < 0) {
                break;
            }
            tmp.add(candidates[i]);
            traceback(candidates, target - candidates[i], ret, tmp, i);
            tmp.remove(tmp.size() - 1);
        }
    }
}


